package com.xp.tinyurl.common.exception;

import com.xp.tinyurl.common.base.ResultVO;
import com.xp.tinyurl.common.base.ResultVOBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Description: exception handler
 * @Author:
 * @Date: 2020/7/10 10:00
 */
@Slf4j
@ControllerAdvice
public class BaseExceptionHandler {

    /**
     * 处理自定义业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public Object errorBizException(BizException e) {
        log.error(e.getMessage(), e);
        return failure(e);
    }

    /**
     * 处理自定义业务异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = AuthException.class)
    @ResponseBody
    public Object errorAuthException(AuthException e) {
        log.error(e.getMessage(), e);
        return ResultVOBuilder.unAuthErr(e.getMessage(), "");
    }

    /**
     * 处理异常
     * @param e
     * @return
     */
    @ExceptionHandler(value ={ Exception.class, NullPointerException.class})
    @ResponseBody
    public Object errorException(Exception e) {
        log.error(e.getMessage(), e);
        return failure(e);
    }

    public static ResultVO failure(Throwable e){
        if(e instanceof BizException){
            return ResultVOBuilder.failure(e.getMessage());
        }else{
            return ResultVOBuilder.failure("服务端内部异常");
        }
    }

}
